package com.vidmt.api.modules.sys.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import com.github.pagehelper.PageInfo;
import com.vidmt.api.common.exceptions.BadParamException;
import com.vidmt.api.common.utils.AES128Coder;
import com.vidmt.api.common.utils.CommUtil;
import com.vidmt.api.common.utils.SpringUtil;
import com.vidmt.api.common.utils.StrUtil;
import com.vidmt.api.modules.sys.Enums.PayType;

public class VUtil {
	private static final Logger log = LoggerFactory.getLogger(VUtil.class);
	private static final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
	private static final String PHONE_PATTERN = "^1[3578]\\d{9}$";
	private static final ResourceLoader resourceLoader = new DefaultResourceLoader();

	public static String time14() {
		return df.format(new Date());
	}

	public static double float6(double d) {
		return Double.parseDouble(String.format("%.6f", d));
	}

	public static boolean isPhoneFmt(String phone) {
		return phone.matches(PHONE_PATTERN);
	}

	public static String toPageHtml(PageInfo<?> page) {
		StringBuilder sb = new StringBuilder("<ul class='am-pagination'></ul>");
		sb.append("<script>var pagination=new Pagination({");
		sb.append("wrap:$('.am-pagination'),");
		sb.append("count:" + page.getPages() + ",");
		sb.append("current:" + page.getPageNum() + ",");
		sb.append("prevText:'上一页',");
		sb.append("nextText:'下一页',");
		sb.append("callback:function(page) {console.log(page);}");
		sb.append("});</script>");
		return sb.toString();
	}

	public static Resource loadClasspathResource(String path) {
		return resourceLoader.getResource(path);
	}

	public static String getNotifyUrl(PayType paytype) {
		String rawurl = PropUtil.get(PropUtil.KEY_SYS_PAY_NOTIFY_URL);
		if (!CommUtil.isEmpty(rawurl)) {
			return rawurl.replace(PropUtil.VAR_PAYTYPE, paytype.name().toLowerCase());
		}
		return null;
	}

	public static String getRealPath(String path) {
		return SpringUtil.getServletContext().getRealPath(path);
	}

	public static String[] decodeAcctxt(String acctxt, String keystr) throws BadParamException {
		try {
			byte[] key = StrUtil.bytesutf8(keystr);
			AES128Coder des = new AES128Coder(key);
			String plain = StrUtil.newutf8(des.decrypt(acctxt));
			return plain.split(":");
		} catch (Exception e) {
			throw new BadParamException(new IllegalArgumentException("acctxt error", e));
		}
	}
}
